//
//  JsonUtil.m
//  school
//
//  Created by ci123 on 15-3-26.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "JsonUtil.h"

@implementation JsonUtil


/**
    转换dictionary字典的key－value成json串
    Example:
    dict = [NSDictionary dictionaryWithObjectsAndKeys:@"kobe",@"name",@"38",@"age",@"USA",@"country", nil];
    
    out:
    {
        "name" : "kobe",
        "age" : "38",
        "country" : "USA"
    }
 */
+(NSString *)convertDictionaryToJson:(NSDictionary *)dict{
    
    NSString *json = @"";
    if ([NSJSONSerialization isValidJSONObject:dict])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    //NSLog(@"Convert dictionary -> json: %@",json);
    return json;
}

+(NSDictionary *)convertJsonToDictionary:(NSString *)jsonString{
    //TODO
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    return [self convertDataToDictionary:data];
}

+(NSDictionary *)convertDataToDictionary:(NSData *)data{
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    return dict;
}

@end
